package jdbc;

import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author oldliu
 * @since 1.0
 */
public class TransferBank {
    public static void main(String[] args) {
        doTransfer("tanghaiyang","xuerpeng",200);
    }
    /**
     *
     * @param from 转出账号
     * @param to  转入账号
     * @param money 转多少钱
     */
    public static void doTransfer(String from,String to,double money){
        Connection con = DBUtil.get();
        PreparedStatement ps=null;
        PreparedStatement ps2=null;
        String sql="update bank set balance=balance-? where acno=?";
        String sql2="update bank set balance=balance+? where acno=?";
        try {
            con.setAutoCommit(false);
            ps=con.prepareStatement(sql);
            ps.setDouble(1,money);
            ps.setString(2,from);
            int r1=ps.executeUpdate();
            ps2=con.prepareStatement(sql2);
            ps2.setDouble(1,money);
            ps2.setString(2,to);
            int r2=ps2.executeUpdate();
            if(r1==1&&r2==1){
                con.commit();
            }else{
                con.rollback();
            }
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {

            }
            e.printStackTrace();
        }finally {
            DBUtil.close(ps);
            DBUtil.close(ps2);
            DBUtil.close(con);
        }

    }
}
